package fun.flyee.android.pengshan.services;

import android.app.Notification;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMap;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Polygon;
import com.amap.api.track.query.entity.Point;
import com.hcvsa.HCVSAService;

import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import fun.flyee.android.pengshan.AppContex;
import fun.flyee.android.pengshan.Storage;
import fun.flyee.android.pengshan.api.ApiClient;
import fun.flyee.android.pengshan.models.GeoRail;
import fun.flyee.android.pengshan.models.GpsTimeSetting;
import fun.flyee.android.pengshan.models.UserInfo;
import fun.flyee.android.pengshan.utils.DateUtil;
import fun.flyee.android.pengshan.utils.Logger;
import fun.flyee.android.pengshan.utils.NotificationUtilsTimer;
import fun.flyee.android.pengshan.utils.Util;
import fun.flyee.pengshan.social.BuildConfig;
import fun.flyee.pengshan.social.R;

public class AppService extends HCVSAService {

    GpsTimeSetting setting;

    private PowerManager.WakeLock wakeLock = null;
    private NotificationUtilsTimer notificationUtilsTimer;
    private Notification notification;

    private Timer mOnlineTimer = new Timer();
    UserInfo user;
    Tracker tracker;
    private boolean needTrace = false;

    @Override
    public void onCreate() {
        super.onCreate();
        this.setForeground();
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, AppService.class.getName());
        wakeLock.acquire();
        user = Storage.getUser();
        if (user != null) {
            loadSetting();
            online();
            List<String> arr = Util.asList("bf4c8b98c05b4b4c", "732edd4feb634d98", "39f3fa06582843de");
            if (user.roleIds != null
                    && user.roleIds.size() > 0) {
                try {
                    arr.retainAll(user.roleIds);
                    needTrace = arr.size() > 0;
                } catch (Exception e) {
                    e.printStackTrace();
                    ApiClient.log(user.id, "create", "service.onCreate");
                }
            }
        }
    }

    private void setForeground() {
        if (Build.VERSION.SDK_INT >= 26) {
            notificationUtilsTimer = new NotificationUtilsTimer(AppContex.getContext());
            Notification.Builder builder = notificationUtilsTimer.getAndroidChannelNotification(getString(R.string.app_name), "数据同步中");
            builder.setSmallIcon(R.mipmap.ic_work);
            builder.setAutoCancel(false);
            notification = builder.build();
        } else {
            //获取一个Notification构造器
            Notification.Builder builder = new Notification.Builder(this);

            builder.setContentTitle(getString(R.string.app_name)) // 设置下拉列表里的标题
                    .setAutoCancel(false)
                    .setSmallIcon(R.mipmap.ic_work) // 设置状态栏内的小图标
                    .setContentText(getString(R.string.running)) // 设置上下文内容
                    .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

            notification = builder.build(); // 获取构建好的Notification
        }
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        if (Build.VERSION.SDK_INT >= 26) {
            startForeground(3, notification);
        }
    }

    private void online() {
        mOnlineTimer.schedule(new OnlineTimerTask(), 30000, 300000);
    }

    public void checkTrack() {
        if (this.setting == null || user == null || needTrace) return;
        if (setting.checkInTime()) {
            if (tracker == null) {
                tracker = new EagleTracker(getApplicationContext(), user.id);
                tracker.start();
                Logger.i("trace-status: start");
                ApiClient.log(user.id, "track", "track.restart");
            } else {
                Logger.i("trace-status: running");
            }
        } else {
            if (tracker != null) {
                tracker.destroy();
                tracker = null;
                Logger.i("trace-status: stop");
                ApiClient.log(user.id, "track", "track.stop");
            } else {
                Logger.i("trace-status: nothing");
            }
        }
    }

    private void loadSetting() {
        GpsTimeSetting.loadSetting(s -> {
            this.setting = s;
            ApiClient.log(user.id, "gps-setting", JSONObject.toJSONString(this.setting));
            goon();
        });
    }

    private synchronized void goon() {
        if (this.setting != null && this.user != null) {
            ApiClient.log(user.id, "track", "track.start");
            tracker = new EagleTracker(getApplicationContext(), user.id);
            tracker.start();
        }
    }

    @Override
    public void onDestroy() {
        ApiClient.log(user.id, "200", "service.onDestroy");
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        stopForeground(true);
        if (mOnlineTimer != null) {
            try {
                mOnlineTimer.cancel();
            } catch (Exception e) {

            }
            mOnlineTimer = null;
        }
        if (tracker != null) {
            tracker.destroy();
            tracker = null;
        }
        this.user = null;
        super.onDestroy();
    }

    class OnlineTimerTask extends TimerTask {

        @Override
        public void run() {
            setForeground();
            checkTrack();
            ApiClient.get("/back-stage/app/online", null, (resp) -> {
                if (BuildConfig.DEBUG) {
                    Logger.i(resp.code + " : " + resp.msg);
                }
            });

            
        }
    }

}
